<template>
<div>
  <q-list>
    <q-list-header>{{title}} {{"(共"+total+")"}}</q-list-header>
    <q-item multiline v-for="obj in objs"
            :obj-id="obj._id"
            :key="obj.key"
            link
            :to="{ name: itemEndpoint, params: { itemId: obj._id , itemName: obj.name}}"
            >
      <q-item-main :label="obj.name" label-lines="4"
                   :sublabel="subLabel(obj)" sublabel-lines="4"
                   />
      <q-item-side right :stamp="obj._created">
      </q-item-side>
    </q-item>
  </q-list>
  <q-pagination
    v-model="pageAt" :max="pageMax" @input="loadObjs()"
    boundary-links
    :max-pages="8"
    />
</div>
</template>

<script>
import {
  mapState
} from 'vuex'

export default {
  name: 'DescribedObjList',
  props: [
    'title',
    'itemEndpoint',
    'url'
  ],
  data () {
    return {
      objs: [],
      pageMax: 1,
      pageAt: 1,
      total: 0
    }
  },
  computed: {
    ...mapState('subtoken', [
      'token'
    ])
  },
  mounted: function () {
    if (this.token === '') {
      this.objs = []
    } else {
      this.loadObjs()
    }
  },
  methods: {
    subLabel (obj) {
      return [obj.title, obj.description].join('\n')
    },
    loadObjs () {
      this.$axios.get(
        this.$store.state.api.apiRoot +
          this.url +
          'page=' + this.pageAt
      )
        .then(
          (response) => {
            this.objs = response.data._items
            this.total = response.data._meta.total
            this.pageMax = Math.ceil(
              response.data._meta.total /
                response.data._meta.max_results)
          })
        .catch(
          (error) => {
            console.log(error)
            this.objs = []
          })
    }
  },
  watch: {
    token: function (new_, old_) {
      if (new_ === '') {
        this.data = []
        return
      }
      this.loadObjs()
    },
    url: function (new_, old_) {
      this.loadObjs()
    }
  }

}
</script>

<style>
</style>
